import { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, message } from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import request from '@/utils/request';

const apiUrl = '/api/services/app/User/';
const PswUpdate = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [datas, setDatas] = useState({});
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    if (props.userId) {
      getData(props.userId);
    }
  }, [props.userId]);

  const getData = (id: number) => {
    if (id > 0) {
      setLoading(true);
      request(apiUrl + 'Get', {
        method: 'GET',
        params: {id},
      }).then((response) => {
        if (response && response.success) {
          const result = response.result;
          setDatas(result);
          formRef.current.setFieldsValue({ user: result });
        }
        setLoading(false);
      });
    }
  };

  const onFinish = (values: any) => {
    values.user.userId = props.userId;
    request(apiUrl + 'ChangePassword', {
      method: 'POST',
      data: values.user,
    }).then((response) => {
      if (response && response.success) {
        message.success(intl.formatMessage({id:'pages.passwordModifiedSuccess'}));
      }
      setLoading(false);
    });
  };

  const checkPsw = (rule: any, value: any, callback: any) => {
    if (value) {
      const datas = formRef.current.getFieldsValue();
      if (value == datas.user.oldPassword) {
        callback(<FormattedMessage id="pages.newOldPasswordCannotSame" />);
      } else if (value != datas.user.confirmPsw && datas.user.confirmPsw) {
        callback(<FormattedMessage id="pages.comfirm.password.same" />);
      } else {
        callback();
      }
    } else {
      callback(<FormattedMessage id="pages.newPassword.required" />);
    }
  };

  const confirmPsw = (rule: any, value: any, callback: any) => {
    if (value) {
      const datas = formRef.current.getFieldsValue();
      if (value != datas.user.newPassword) {
        callback(<FormattedMessage id="pages.comfirm.password.same" />);
      } else {
        callback();
      }
    }
    callback();
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 17 },
  };

  return (
    <div>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Form.Item
          name={['user', 'oldPassword']}
          label={<FormattedMessage id="pages.oldPassword" />}
          rules={[{ required: true, message: intl.formatMessage({id:'pages.oldPassword.required'})}]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item
          name={['user', 'newPassword']}
          label={<FormattedMessage id="pages.newPassword" />}
          rules={[{ required: true, validator: checkPsw }]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item
          name={['user', 'confirmPsw']}
          label={<FormattedMessage id="pages.confirmPsw" />}
          rules={[
            {
              required: true,
              validator: confirmPsw,
            },
          ]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>
          <Button type="primary" htmlType="submit" loading={loading}>
            <FormattedMessage id="pages.save" />
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default connect(({ user }: API.IConnectState) => ({
  currentUser: user.currentUser,
}))(PswUpdate);
